package com.utils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.filters.ColorMatrixFilter;
	import flash.filters.DropShadowFilter;
	import flash.filters.GlowFilter;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.utils.Dictionary;
	
	/**
	 * 按钮组件 
	 * @author Mr.Lu
	 * @param 可以创建矢量图按钮,也可以加载图片作为按钮
	 * @param 影片剪辑调用register()静态方法
	 */	
	public class ButtonModule extends MovieClip
	{
		private static var _registerList:Array;
		private static var _imageDataSource:Dictionary = new Dictionary();
		public static var curClickCount:int = 0;
		private var _regExpArr:Array = ['.png','.PNG','.jpg','.JPG','.jpeg','.JPEG','.gif','.Gif','.GIF'];//存储图片路径可能存在的字符
		private var _bgShapeProperty:Object;
		private var _textProperty:Object;
		private var _btnText:TextField;
		private var _btnStrList:Array;
		private var _target:*;
		private var _shape:Shape;
		private var _loader:Loader;
		private var _image:Bitmap;
		private var _bitmapData:BitmapData;
		private var _clickCallBack:Function;
		private var _loopDealy:int =0;
		private var _font:String;
		private var _size:int;
		private var _color:String;
		private var _txtFilters:Array;
		private var _label:String;
		
		/**
		 * @param target null(绘制矢量按钮) 图片路径(将加载的图片作为按钮)
		 * @param btnStrList 按钮显示的文字数组     每次点击会根据数组长度替换按钮文字
		 * @param textProperty 设置文字的相关属性 {font:'Verdana',size:14,color:#FFcc00,filters:[new DropShadowFilter(0,45,0,1,2,2,10)]}
		 * @param bgShapeProperty 设置背景的相关属性 {color:0xFFFFFF,alpha:1,width:80,height:30,ellipseWidth:10,ellipseHeight:10}
		 */		
		public function ButtonModule(target:*=null,btnStrList:Array=null,textProperty:Object= null,bgShapeProperty:Object= null,clickCallBack:Function=null,loopDealy:int = 1){
			_btnStrList = btnStrList;
			_textProperty = textProperty;
			_bgShapeProperty = bgShapeProperty;
			_clickCallBack = clickCallBack;
			_loopDealy = loopDealy;
			checkTargetType(target);
			this.buttonMode = true;
		}
		
		private function checkTargetType(target:*=null):void
		{
			_target = target;
			
			if(!_target){//绘制矢量图按钮
				createBtn();
			}else if(getRegExpResult(_target)){//图片
				createImageBtn();
			}else if(_target is Bitmap){
				createBitmapBtn(_target);
			}else{
				if(target is MovieClip){
					throw Error('MovieClip直接调用register()!');
				}else{
					throw Error('错误的文件格式!');
				}
			}
			
			if(_btnStrList && _btnStrList.length>0) createTxt();
			createListeners();
		}
		
		private function createBitmapBtn(bitmap:Bitmap):void
		{
			_image = bitmap;
			this.addChild(_image);
			_image.width = getProperty('width',_image.width);
			_image.height = getProperty('height',_image.height);
			setBtnTextPoint();
		}
			
		
		//判断是否是图片
		private function getRegExpResult(value:String = ''):Boolean{
			for (var i:int = 0; i < _regExpArr.length; i++) 
			{
				var reg:RegExp =  new RegExp(_regExpArr[i]);
				if(reg.test(value)) return true;
			}
			return false;
		}
		
		/**
		 * 添加文本
		 * @param targetContain 文本容器
		 * @param params 要设置的属性
		 * new DropShadowFilter(0,45,0,1,2,2,10)
		 */		
		public function createTxt():void
		{
			_btnText = new TextField();
			this.addChild(_btnText);
			_btnText.mouseEnabled = false;
			//_btnText.background = true;
			//_btnText.backgroundColor = 0xFF0000;
			_font = getProperty('font','Verdana','_textProperty');
			_size = getProperty('size',14,'_textProperty');
			_color = getProperty('color','#000000','_textProperty');
			_txtFilters = getProperty('filters',[],'_textProperty');
			_btnText.filters = _txtFilters;
			_btnText.htmlText = '<font face="'+_font+'" size="'+_size+'" color="'+_color+'"><b>'+ _btnStrList[0] +'</b></font>';
			_btnText.width = _btnText.textWidth+5;
			_btnText.height = _btnText.textHeight+5;
			setBtnTextPoint();
		}
		
		/**改变按钮文字*/		
		private function changeBtnStr(index:int):void
		{
			if(!_btnStrList || _btnStrList.length == 0) return;
			_label = _btnStrList[index%_btnStrList.length];
			_btnText.htmlText = '<font face="'+_font+'" size="'+_size+'" color="'+_color+'"><b>'+ _label +'</b></font>';
		}
		
		/**设置文本的坐标*/		
		private function setBtnTextPoint():void
		{
			if(!_btnText) return;
			_btnText.x = (this.width - _btnText.width)/2;
			_btnText.y = (this.height - _btnText.height)/2;
		}
		
		
		/**创建按钮背景*/	
		private function createBtn():void
		{
			_shape = new Shape();
			this.addChild(_shape);
			_shape.graphics.beginFill(getProperty('color',0xFFFFFF),getProperty('alpha',1));
			_shape.graphics.drawRoundRect(0,0,getProperty('width',80),getProperty('height',30),getProperty('ellipseWidth',10),getProperty('ellipseHeight',10));
			_shape.graphics.endFill();
			_shape.filters = [new GlowFilter(getProperty('filterColor',0xAAAAAA),getProperty('filterAlpha',.5),getProperty('filterBlurX',6.0),
				getProperty('filterBlurY',6.0),getProperty('filterStrength',3),getProperty('filterQuality',1),
				getProperty('filterInner',true)),new DropShadowFilter(0)];
		}
		
		/**创建图片按钮*/		
		private function createImageBtn():void
		{
			if(_imageDataSource[_target]){
				_image = new Bitmap(BitmapData(_imageDataSource[_target]).clone());
				this.addChild(_image);
				return;
			}
			_bitmapData = new BitmapData(getProperty('width',80),getProperty('height',30),true,0);
			_image = new Bitmap(_bitmapData);
			this.addChild(_image);
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onCompleteHandler);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onIoErrorHandler);
			_loader.load(new URLRequest(_target));
		}
		
		private function onIoErrorHandler(e:IOErrorEvent):void
		{
			trace('IOErrorEvent:' + e.text);
		}
		
		/**加载完毕将数据存入资源池*/		
		private function onCompleteHandler(e:Event):void
		{
			_imageDataSource[_target] = Bitmap(_loader.content).bitmapData;
			_image.bitmapData = BitmapData(_imageDataSource[_target]).clone();
			_bitmapData = null;
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,onCompleteHandler);
			_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onIoErrorHandler);
			_loader = null;
			_image.width = getProperty('width',_image.width);
			_image.height = getProperty('height',_image.height);
			setBtnTextPoint();
		}		
		
		/**添加侦听器*/		
		private function createListeners():void
		{
			if(!this.hasEventListener(MouseEvent.ROLL_OVER)){
				this.addEventListener(MouseEvent.ROLL_OVER,onRollHandler);
			}
			if(!this.hasEventListener(Event.REMOVED_FROM_STAGE)){
				this.addEventListener(Event.REMOVED_FROM_STAGE,onRemoveFromStageHandler);
			}
		}
		
		private function onRollHandler(e:MouseEvent):void
		{
			this.addEventListener(MouseEvent.ROLL_OUT,onMouseHandler);
			this.addEventListener(MouseEvent.MOUSE_UP,onMouseHandler);
			this.addEventListener(MouseEvent.MOUSE_DOWN,onMouseHandler);
			McEffect.instance.knockEffect(this);
			//this.filters = [new GlowFilter(0x00CCFF,1,3,3,2,1)];
		}
		
		private function onMouseHandler(e:MouseEvent):void
		{
			if(e.type == MouseEvent.ROLL_OUT){
				McEffect.instance.removeEffect(this);
			}else if(e.type == MouseEvent.MOUSE_UP){
				McEffect.instance.removeEffect(this);
			}else if(e.type == MouseEvent.MOUSE_DOWN){
				McEffect.instance.dizzyEffect(this);
				++curClickCount;
				changeBtnStr(curClickCount);
				if(curClickCount % _loopDealy == 0 && _clickCallBack is Function) _clickCallBack();
			}
		}		
		
		/**移除相关事件*/		
		private function onRemoveFromStageHandler(e:Event):void
		{
			while(this.numChildren){
				removeChildAt(0);
			}
			if(_image) _image = null;
			if(_shape) _shape = null;
			this.removeEventListener(Event.REMOVED_FROM_STAGE,onRemoveFromStageHandler);
			this.removeEventListener(MouseEvent.ROLL_OVER,onRollHandler);
			this.removeEventListener(MouseEvent.ROLL_OUT,onMouseHandler);
			this.removeEventListener(MouseEvent.MOUSE_UP,onMouseHandler);
			this.removeEventListener(MouseEvent.MOUSE_DOWN,onMouseHandler);
		}
		
		
		/**获取设置的属性值*/		
		private function getProperty(key:String,defaultValue:*,property:Object = '_bgShapeProperty'):*
		{
			if(this[property] && this[property][key]){
				return this[property][key];
			}else{
				return defaultValue;
			}
		}
		
		/**注册按钮组件*/		
		public static function register(handler:MovieClip, buttonText:String, txt:String = "txtName"):void
		{
			if(!_registerList) _registerList = [];
			_registerList[handler.name] = new BtnRegister(handler, buttonText, txt);
		}
		
		/**解除按钮注册*/		
		public static function cancelRegister(handler:MovieClip=null):void{
			for(var key:String in _registerList) 
			{
				if(handler && handler.name == key){
					_registerList[key].removeListens();
				}else{
					_registerList[key].removeListens();
				}
			}
		}
		
		public function get label():String
		{
			return _label;
		}
		
		/**
		 * 设置按钮是否接受鼠标事件，并添加滤镜
		 * @param value
		 */		
		public function set enable(value:Boolean):void
		{
			this.mouseEnabled = value;
			this.mouseChildren = value;
			if(value){
				this.filters = [];
			}else{
				this.filters = [new ColorMatrixFilter([.3,.3,.3,0,0,.3,.3,.3,0,0,.3,.3,.3,0,0,0,0,0,1,1])];
			}
		}
		
		
		
	}
}

import flash.display.DisplayObject;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
import flash.geom.ColorTransform;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

class McEffect{
	public static const instance:McEffect = new McEffect();
	public function McEffect(){
		if(instance) throw Error('不能重复实例化!')
	}
	
	/**泛白效果*/	
	public function knockEffect(display:DisplayObject):void{
		var colorInfo:ColorTransform = display.transform.colorTransform;
		colorInfo.redOffset = 50;
		colorInfo.greenOffset = 50;
		colorInfo.blueOffset = 50;
		display.transform.colorTransform = colorInfo;
	}
	
	/**移除效果*/	
	public function removeEffect(display:DisplayObject):void{
		var colorInfo:ColorTransform = display.transform.colorTransform;
		colorInfo.redOffset = 0;
		colorInfo.greenOffset = 0;
		colorInfo.blueOffset = 0;
		display.transform.colorTransform = colorInfo;
		display.filters = null; //将所属的滤镜移除
	}
	
	/**灰色效果*/	
	public function dizzyEffect(display:DisplayObject):void{
		var colorInfo:ColorTransform = display.transform.colorTransform;
		colorInfo.redOffset = -80;
		colorInfo.greenOffset = -80;
		colorInfo.blueOffset = -80;
		display.transform.colorTransform = colorInfo;
	}
}


class BtnRegister{
	private var _target:MovieClip;
	private var _frames:int;
	private var _txt:String;
	private var _buttonText:String;
	
	public function BtnRegister(target:MovieClip, buttonText:String, txt:String = "txtName"){
		_target = target;
		_buttonText = buttonText;
		_txt = txt;
		_frames = _target.totalFrames;
		_target.gotoAndStop(1);
		_target.mouseChildren = false;
		_target.buttonMode = true;
		if(!_target.hasEventListener(MouseEvent.ROLL_OVER)){
			_target.addEventListener(MouseEvent.ROLL_OVER,onRollOverHandler);
		}
		setTextField();
	}
	
	private function onRollOverHandler(e:MouseEvent):void
	{
		_target.addEventListener(MouseEvent.ROLL_OUT,onRollOutHandler);
		_target.addEventListener(MouseEvent.MOUSE_UP,onMouseHandler);
		_target.addEventListener(MouseEvent.MOUSE_DOWN,onMouseHandler);
		_frames >= 3 ? _target.gotoAndStop(2) : _target.gotoAndStop(1);
	}	
	
	private function onMouseHandler(e:MouseEvent):void
	{
		if(e.type == MouseEvent.MOUSE_UP){
			_frames >= 3 ? _target.gotoAndStop(2) : _target.gotoAndStop(1);
		}else{
			_frames >= 3 ? _target.gotoAndStop(3) : _target.gotoAndStop(2);
		}
	}
	
	private function onRollOutHandler(e:MouseEvent):void
	{
		_target.removeEventListener(MouseEvent.ROLL_OUT,onRollOutHandler);
		_target.removeEventListener(MouseEvent.MOUSE_UP,onMouseHandler);
		_target.removeEventListener(MouseEvent.MOUSE_DOWN,onMouseHandler);
		_target.gotoAndStop(1);
	}		
	
	private function setTextField():void{
		if(_target[_txt]){
			(_target[_txt] as TextField).htmlText = _buttonText;
		}else{
			var textField:TextField = this.getTargetTxt();
			
			if(textField != null){
				textField.htmlText = _buttonText;
			}else{
				addTextField();
			}
		}
	}
	
	private function getTargetTxt():TextField
	{
		for (var i:int = 0; i < _target.numChildren; i++) 
		{
			if(_target.getChildAt(i) is TextField) return _target.getChildAt(i) as TextField
		}
		return null;
	}
	
	/**无文本，添加文本*/		
	private function addTextField():void
	{
		var txt:TextField = new TextField();
		txt.autoSize = TextFieldAutoSize.LEFT;
		txt.filters = [new GlowFilter(0,1,2,2,18)];
		txt.htmlText = _buttonText;
		txt.mouseEnabled = false;
		_target.addChild(txt);
		txt.x = (_target.width - txt.width)/2;
		txt.y = (_target.height - txt.height)/2;
	}
	
	public function removeListens():void{
		_target.removeEventListener(MouseEvent.ROLL_OVER,onRollOverHandler);
		_target.removeEventListener(MouseEvent.ROLL_OUT,onRollOutHandler);
		_target.removeEventListener(MouseEvent.MOUSE_UP,onMouseHandler);
		_target.removeEventListener(MouseEvent.MOUSE_DOWN,onMouseHandler);
	}
	
	
	
	
	
	
	
}